#include "zipio.hpp"

zipIO::zipIO( io_type type , filterList *l )
: filterIO( type , l )
{
    	m_lev = FOUR;
}

zipIO::~zipIO()
{
    //dtor
}

bool zipIO :: on_forward( size_t len , const char * data , err_code &err , size_t& rlen , char ** rd )
{
	bool ret = false;
	size_t  s = compressBound( len );

	*rd = ( char *)malloc( s );
	if( *rd != nullptr ){
		// 压缩操作
	int e = compress2( ( unsigned char *)*rd ,(unsigned long *) &rlen ,(const unsigned char *)data , len , (int) m_lev );
		if( e == Z_OK ) ret = true;
		else{
			free( *rd );
			*rd = nullptr;
			rlen = 0;
		}
	}
	return ret;
}

bool zipIO :: on_backward( size_t len , const char * data , err_code &err , size_t& rlen , char ** rd  )
{
	bool ret = false;
	if( data == nullptr ) return false;
	if( len < sizeof( size_t ) ) return false;

	size_t rl = ((size_t*)data)[ 0 ];

	*rd = (char *) malloc( rl );
	if( *rd != nullptr ){
	int e = uncompress( ( unsigned char *)*rd , (unsigned long *)&rlen , (const unsigned char *)(data + 4) , len - 4 );
		if( e == Z_OK ) ret = true;
		else{
			free( *rd );
			*rd = nullptr;
			rlen = 0;
		}
	}

	return ret;
}
